package com.lolaage.tracks.adapter;

import android.util.Log;

import com.lolaage.tracks.MyLocationPolicy;

public class AdaptiveLocationPolicy implements MyLocationPolicy
{
    private final long minInterval;
    private final long maxInterval;
    private final int minDistance;
    private final int maxDistance;
    // The time the user has been idle at the current location, in milliseconds.
    private long idleTime;
    private int  idleDistance;
    private float  preSpeed;
    
    public AdaptiveLocationPolicy(
            long minInterval, long maxInterval
            , int minDistance, int maxDistance)
    {
        this.minInterval = minInterval;
        this.maxInterval = maxInterval;
        this.minDistance = minDistance;
        this.maxDistance = maxDistance;
    }

    /*
     * Returns an interval half of the idle time, but bounded by minInteval and
     * maxInterval.
     */
    @Override
    public long getDesiredPollingInterval()
    {
        long desiredInterval = idleTime / 2;
        // Round to second to avoid setting the interval too often
        desiredInterval = (desiredInterval / 1000) * 1000;
        return Math.max(Math.min(maxInterval, desiredInterval), minInterval);
    }

    @Override
    public int getDesiredPollingDistance()
    {
        int desiredDistance = idleDistance;
        // Round to second to avoid setting the interval too often
        desiredDistance = (desiredDistance / 100) * 100;
        return Math.max(Math.min(maxDistance, desiredDistance), minDistance);
    }

    @Override
    public void updateIdleTime(long newIdleTime, int newIdleDistance)
    {
        idleTime = newIdleTime;
        idleDistance = newIdleDistance;
        // 平均速度
        float curSpeed = newIdleDistance/(newIdleTime/1000);
        if(preSpeed == 0)
        {
            preSpeed = curSpeed;
        }else
        {
            // 平均速度差值
            int deltSpeed = (int)(curSpeed - preSpeed);
            Log.d("AdaptiveLocationPolicy", "--->preSpeed="+preSpeed+";curSpeed="+curSpeed+";deltSpeed="+deltSpeed);
            if(deltSpeed == 0)
            {
                // 类 静止 或者 匀速
                idleDistance = maxDistance;
            }else
            if(deltSpeed > 0)
            {
                // 类 加速
                idleDistance = minDistance;
            }else 
            {
                // 类 减速
            }
            // 交换
            preSpeed = curSpeed;
        }
    }
}
